package solution;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;

        int iFlag = 0;
        int jFlag = 0;

        int nnL = 0;
        int mmL = 0;
        int nnR = n; //边界
        int mmR = m; //边界

        int count = 0;
        // Set<Integer> ret = new LinkedHashSet<>();
        List<Integer> ret = new ArrayList<>();
        while (ret.size() < n * m) {
            int j = mmL;
            int i = nnL;
            while (ret.size() < n * m && j < mmR && j >= 0) {
                ret.add(matrix[i][j++]);
                count++;
            }
            j--;
            i++;
            while (ret.size() < n * m && i < nnR && i >= 0) {
                ret.add(matrix[i++][j]);
                count++;
            }
            i--;
            j--;
            while (ret.size() < n * m && j > mmL && j < m) {
                ret.add(matrix[i][j--]);
                count++;
            }
            while (ret.size() < n * m && i > nnL && i < n) {
                ret.add(matrix[i--][j]);
                count++;
            }
            j++;
            i++;
            nnL++;
            mmL++;
            nnR--;
            mmR--;
        }

        return ret;
    }
}